import Vue from 'vue'
import Axios from 'axios'
import router from '../router/index'

// const axios = Axios.create({
//   // baseURL: process.env.NODE_ENV === 'development' ? '' : '',
// })

export default (url, method = 'get', data = {}) => {
  return Axios({
    url,
    method,
    data
  })
}

// restful风格（请求方式和操作行为的映射）
const restFullMapping = {
  get: 'view',
  post: 'add',
  put: 'edit',
  delete: 'delete'
}

// 请求拦截器
Axios.interceptors.request.use((req) => {
  // console.log(req.url);
  console.log(req.method);
  if(req.url !== '/login') {
    req.headers.Authorization = sessionStorage.getItem('token')
    // 判断非权限范围内的请求
    /** restful风格请求
     * get请求: view
     * post请求：add
     * put请求：edit
     * delete请求: delete
     * 
    */    
    const routingPermissions = router.currentRoute.meta // 当前路由的权限
    const reqMethods = restFullMapping[req.method] // 根据请求，得到的是哪种操作
    if(routingPermissions && routingPermissions.indexOf(reqMethods) === -1) { // 当前路由中是否含有请求方式对应的权限      
      Vue.prototype.$message({
         message: '没有访问的权限',
         type: 'warning'
     }); 
      return Promise.reject(new Error('没有访问的权限'))
    }
  }
  return req
})

// 响应拦截器
Axios.interceptors.response.use((req) => {  
  // console.log(req.status === 401)
  if(req.status === 401) {
    router.push('/login')
    sessionStorage.clear()
    window.location.reload()
  }
  return req
})